/*
 * 创建时间：2011-3-15 下午03:25:17
 * 工程名称：XTeam-acs4j
 * 文   件  名：com.xteam.asc4j.db.AcsSessions.java
 * Author:Leo
 * 
 */
package com.xteam.db;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.tangkf.utils.CommonUtils;
import com.xteam.purview.base.AppContextUtils;
import com.xteam.tools.config4j.cfg.ConfigBuilder;
import com.xteam.tools.config4j.cfg.ConfigNode;

/**
 * Hibernate session 提供者
 * @author Leo
 */
public class SessionProvider {
	
	private static Logger						log				= LogManager.getRootLogger();
	private static SessionFactory				sessionFactory;

	private static ConfigNode					root;

	private static final ThreadLocal<Session>	sessionCache	= new ThreadLocal<Session>();

	static {
		try {
			ConfigBuilder cb = new ConfigBuilder("/system-config.xml");
			root = cb.getRoot();
			initSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获得SessionFatory对象
	 * @return SessionFactory
	 * @author:Leo
	 */
	public static SessionFactory initSessionFactory() {
		if (null != sessionFactory) {// 工厂类不为空，直接返回
			return sessionFactory;
		}
		
		if (null == root) {
			log.error("【读取配置文件失败】...");
			return null;
		}
		ConfigNode cnode = root.getOneChildByName("session-factory-class");
		if (null == cnode) {
			log.error("【读取工厂类(session-factory-class)错误】...");
			return null;
		}
		
		// 不为空，使用用户自定的实现
		if (!CommonUtils.isEmpty(cnode.getNodeValue())) {
			try {
				PurviewSessionFactoryProvider psfactory = (PurviewSessionFactoryProvider) AppContextUtils.getBean(cnode.getNodeValue());
				sessionFactory = psfactory.generateSessionFactory();
				return sessionFactory;
			} catch (Exception e) {
				log.error("【数据源获取出错】："+e.getLocalizedMessage());
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}
	
	/**
	 * 返回 session工厂
	 * @author tangkf  ---2012-1-13
	 * @return
	 */
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}

	/**
	 * 获得当前线程的Session
	 * @return Session
	 * @author:Leo
	 */
	public static Session currentSession() {
		Session session = sessionCache.get();
		if (null == session || !session.isOpen()) {
			if (null == sessionFactory) {
				sessionFactory = initSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			sessionCache.set(session);
		}
		return session;
	}

	/**
	 * 获取一个 hibernate 的session
	 * @see com.xteam.db.SessionProvider.chengjun.dbserver.IHibernate#getSession()
	 */
	public static Session getSession() {
		Session ses = sessionCache.get();
		if (ses == null || !ses.isConnected() || !ses.isOpen()) {
			if (sessionFactory != null) {
				ses = sessionFactory.openSession();
				log.debug(" ------> OPEN SESSION");
				sessionCache.set(ses);
			}
		}
		return ses;
	}

	/**
	 * 将SESSION 放回缓存
	 * @author Implements by tangkf
	 * @Date 2008-1-12
	 * @see com.xteam.db.SessionProvider.chengjun.dbserver.IHibernate#releaseSession(org.hibernate.Session)
	 */
	public static void releaseSession(Session s) {
		if (s != null && s.isConnected() && s.isOpen()) {
			s.flush();
			s.clear();
			s.close();
		}
		sessionCache.set(null);
		sessionCache.remove();
		log.debug(" ------> CLOSE SESSION");
	}
}
